package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper mapper;

    public List<Menu> selectRootMenu() {
        return mapper.selectRootMenu();
    }

    public PageResult query(QueryObject qo) {
        int count = mapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, mapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    public void updateByPrimaryKey(Menu record) {
        mapper.updateByPrimaryKey(record);
    }

    public void insert(Menu record) {
        mapper.insert(record);
    }

    public Menu validateMenuText(String menuText) {
        return mapper.getByMenuText(menuText);
    }

    public void deleteById(Long id) {
        //删除自己
        mapper.deleteByPrimaryKey(id);
        List<Menu> menus = mapper.selectChildrenMenu(id);
        //不为空
        if (menus != null) {
            //遍历删除
            for (Menu menu : menus) {
                //删除自己之后判断是否有子菜单
                    mapper.deleteByPrimaryKey(menu.getId());
                if (menu.getChildren().size() > 0) {
                    deleteById(menu.getId());
                }

            }
        }
    }

    public List<Menu> selectEmployeeMenu() {
        //查询出所有的菜单
        List<Menu> menus = mapper.selectRootMenu();
        //判断登陆用户是不是管理员
        Employee currentUser = UserContext.getCurrentUser();
        //如果不是，就需要对菜单做权限控制
        if(!currentUser.getAdmin()){
            List<Long> ids = mapper.selectByEmployeeId(currentUser.getId());
            //对不是管理员的菜单集合进行操作
            checkMenu(menus,ids);
        }
        return menus;
    }

    public void checkMenu(List<Menu> menus, List<Long> ids) {
        Iterator<Menu> it = menus.iterator();
        while(it.hasNext()){
            Menu menu = it.next();
            if(!ids.contains(menu.getId())){
                it.remove();
                continue;
            }
            //调用自身方法，递归判断子菜单的权限
            if(menu.getChildren().size()>0){
                checkMenu(menu.getChildren(),ids);
            }
        }
    }
}
